"use client"
import { RedoOutlined, SearchOutlined, FilterOutlined, StockOutlined, InsertRowAboveOutlined, HolderOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import type { PopconfirmProps } from 'antd';
import { Space, Table, Tabs, Input, Select, DatePicker, Button, message, Popconfirm, Modal } from 'antd';
import type { TableProps, TabsProps } from 'antd';
import { getdata, deldata, updateShopdata, http_table } from '@/app/request/http';
import { useRouter } from 'next/navigation';
import dayjs from 'dayjs'
import AddData from './utils/page';

const rowSelection: TableProps['rowSelection'] = {
  onChange: (selectedRowKeys: React.Key[], selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User', // Column configuration not to be checked
    name: record.name,
  }),
};
const { Option } = Select;
const Pages = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [getdatas, setGetdata] = useState([])
  let [listdata, setlistdata] = useState([])

  // 顶置
  let handTop = (id) => {
    const taritem = getdatas.find(item => item.id == id)
    const newlist = getdatas.filter(item => item.id != id)
    setGetdata([taritem, ...newlist])
  }

  const columns: TableProps['columns'] = [
    {
      title: '客户名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '客户状态',
      dataIndex: 'age',
      render: (_, ele) => {
        return ele.flag == true ? "跟进" : "已经跟进"
      }
    },
    {
      title: '客户星级',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '首联系人',
      dataIndex: 'topOne',
      key: 'address',
    },
    {
      title: '手机号码',
      dataIndex: 'call',
      key: 'address',
    },
    {
      title: '最后跟进',
      dataIndex: 'time',
      render: (_, a) => {
        return dayjs(a.time).format('YYYY-MM-DD HH:mm:ss')
      },
      sorter: (a, b) => a.time - b.time,
    },
    {
      title: '末跟进天数',
      dataIndex: 'day',
      key: 'address',
      sorter: (a, b) => a.day - b.day,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <button onClick={async () => {
            console.log(record.flag, "111111");


            await updateShopdata({ ...record, flag: !record.flag })
            // console.log(record.flag,"2222");
            update()
          }} disabled={changebox} style={{ border: "none" }}>{record.flag ? '跟进' : <p style={{ color: "#1677ff" }}>已跟进</p>}</button>
          <a onClick={() => {
            showModal()
            setRecord(record)
            settitle("编辑")
          }}>编辑</a>
          <a onClick={() => { handTop(record.id) }}>顶置</a>
          <Popconfirm
            title="删除"
            description="确定要删除本客户吗?"
            onConfirm={() => { confirm(record) }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
        </Space >
      ),
    },
  ];
  let [record, setRecord] = useState<any>({})
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');

  function update() {
    getdata().then(res => {
      return setGetdata(res);
    })
  }

  useEffect(() => {
    update()
  }, [])


  let data: any = [];
  const onChange = (key: string) => {
    console.log(key);
  };

  const confirm: PopconfirmProps['onConfirm'] = (record) => {
    message.success('Click on Yes');
    deldata(record.id)
    update()
  };

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('Click on No');
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '全部客户',
      children: <></>
    },
    {
      key: '2',
      label: '我的客户',
      children: '我的客户',
    },
    {
      key: '3',
      label: '下属客户',
      children: '下属客户',
    },
    {
      key: '4',
      label: '重点客户',
      children: '重点客户',
    },
    {
      key: '5',
      label: '我的协议',
      children: '我的协议',
    },
    {
      key: '6',
      label: '下属协议',
      children: '下属协议',
    },
  ];
  const [position, setPosition] = useState<'start' | 'end'>('end');
  let router = useRouter()

  let [changebox, setchangebox] = useState(true)
  console.log(changebox);


  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  let [title1, settitle1] = useState('')
  let [title2, settitle2] = useState('')
  let [title3, settitle3] = useState('')
  let [title4, settitle4] = useState('')
  let [title, settitle] = useState('')
  return (<>

    <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
    <Modal footer={null} title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>

      <AddData data={record} title={title} record={record} key={new Date().getTime()} onOk={handleOk} />

    </Modal>
    {items.map(item => {
      {
        item.key == "1" ? item.children = <>
          <Input style={{ width: "200px" }} value={title1} onChange={(e) => {
            settitle1(e.target.value)
          }
          } placeholder='搜索关键词' />
          <Select
            placeholder="客户状态"
            allowClear
            style={{ width: "200px", marginLeft: "10px" }}
            value={title2}
            onChange={(value) => {
              settitle2(value)
            }}
          >
            <Option value={true}>跟进</Option>
            <Option value={false}>已经跟进</Option>
          </Select>
          <Select
            placeholder="客户星级"
            allowClear
            style={{ width: "200px", marginLeft: "10px" }}
            value={title3}
            onChange={(value) => {
              settitle3(value)
            }
            }
          >
            <Option value="1">2星</Option>
            <Option value="2">3星</Option>
            <Option value="3">4星</Option>
          </Select>

          <DatePicker value={title4} onChange={(value) => {
            settitle4(value)
          }
          } placeholder='最后跟进' style={{ width: "200px", marginLeft: "10px" }} />

          <Button onClick={async () => {
            console.log(title1, "1111");
            console.log(title2, "2222");

            let res = await http_table(title1, title2, title3, title4)
            setGetdata(res)
          }} style={{ margin: "10px" }} type="primary" icon={<SearchOutlined />} iconPosition={position}>
            查询
          </Button>
          <Button icon={<RedoOutlined />} onClick={() => {
            title1 = "",
              title2 = "",
              title3 = "",
              title4 = "",
              http_table(title1, title2, title3, title4)
            update()
          }
          } iconPosition={position}>
            重置
          </Button>

          <a style={{ marginLeft: "20px" }}>高级筛选 <FilterOutlined /></a>

          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <div style={{ margin: "20px" }}>
              <Button type="primary" onClick={() => {
                showModal();
                settitle("添加")
              }}>添加</Button>
            </div>
            <div style={{ display: "flex", alignItems: "center", marginRight: "250px" }}>
              <div style={{ display: "flex", alignItems: "center" }}><input type="checkbox" checked={!changebox} onChange={() => { setchangebox(changebox =!changebox) }} /><span>跟进模式<HolderOutlined /></span></div>
              <div style={{ margin: "0px 10px" }}><Button><StockOutlined />排序</Button></div>
              <div><Button><InsertRowAboveOutlined />列表</Button></div>
            </div>
          </div>

          <Table pagination={{ defaultPageSize: 7 }} rowSelection={{ type: selectionType, ...rowSelection }} columns={columns} dataSource={getdatas} rowKey="id" />
        </> : ""
      }
    })
    }
  </>
  )
}

export default Pages;
